﻿//------------------------------------------------------------------
// System Name:    smsGateway
// Component:      Common
// Create by:      Evans Liao (evansl@wicresoft.com)
// Create Date:    2010-12-13
//------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Network;
using OpenSmtp;
using OpenSmtp.Mail;

namespace Wicresoft.SMS.Common
{
    public class MailOperation
    {
        // private static ExchangeService service;

        /// <summary>
        /// 在调用静态方法时必须先构造访问邮件的对象
        /// </summary>
        /// <param name="esv">Exchange的版本,目前支持Exchange2007_SP1,Exchange2010,Exchange2010_SP1</param>
        /// <param name="ServerUrl">服务器的地址</param>
        /// <param name="Username">用户名</param>
        /// <param name="Password">密码</param>
        /// <param name="Domain">域</param>
        /// <param name="Email">邮件地址</param>
        public static void InstanceExchangeServerAPI(string evInfo, string ServerUrl, string Username, string Password, string Domain, string Email)
        {
            //if (service == null)
            //{
            //    switch (evInfo)
            //    {
            //        case "Exchange2007_SP1":
            //            service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            //            break;
            //        case "Exchange2010":
            //            service = new ExchangeService(ExchangeVersion.Exchange2010);
            //            break;
            //        case "Exchange2010_SP1":
            //            service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            //            break;
            //        default:
            //            Log.WriteError("{0}", "传入的ExchangeServer版本信息有误");
            //            return;
            //    }
            //    //参数是用户名,密码,域
            //    service.Credentials = new WebCredentials(Username, Password, Domain);
            //    //给出Exchange Server的URL http://xxxxxxx 
            //    service.Url = new Uri(ServerUrl);
            //    //你自己的邮件地址 xxx@xxx.xxx
            //    service.AutodiscoverUrl(Email);
            //}
        }

        private static string UserName;
        private static string Password;
        private static string Host;
        private static int Port;
        private static string Sender;

        public static void InstanceSmtpClient(string username, string password, string host, string port, string sender)
        {
            UserName = username;
            Password = password;
            Sender = sender;
            Host = host;
            Port = Convert.ToInt32(port);

        }

        /// <summary>
        /// 发送邮件, 仅供发送邮件的TASK使用
        /// </summary>
        /// <param name="email">邮件对象属于Wicresoft.SMS.Common</param>
        /// <returns></returns>
        public static bool SendEmail(EmailInfo email)
        {
            if (Host == null)
            {
                // Logger.Error("未配置邮件SMTP帐号信息");
                return false;
            }
            //try
            //{
            //OpenSmtp.Mail.Smtp smtp = new OpenSmtp.Mail.Smtp(Host, UserName, Password,Port);
            Smtp smtp = new Smtp(Host, Port);
            MailMessage mm = BuildMailMessage(email);
            smtp.SendMail(mm);
            return true;
            //EmailMessage em = new EmailMessage(service);
            //em.Subject = email.Subject;
            //em.Body = email.Body;
            //AddEmailAddress2List(email.To, em.ToRecipients);
            //AddEmailAddress2List(email.CC, em.CcRecipients);
            //AddEmailAddress2List(email.BCC, em.BccRecipients);
            //em.SendAndSaveCopy();
            //return true;
            //}
            //catch (Exception ex)
            //{
            //    // Logger.Error("MailOperation.SendEmail " + ex.Message);
            //    return false;
            //}

        }

        private static MailMessage BuildMailMessage(EmailInfo em)
        {
            MailMessage mm = new MailMessage();
            mm.Charset = "UTF-8";
            mm.From = new EmailAddress(Sender);
            AddEmailAddress2List(em.To, mm.To);
            AddEmailAddress2List(em.CC, mm.CC);
            AddEmailAddress2List(em.BCC, mm.BCC);
            mm.Subject = em.Subject;
            mm.HtmlBody = em.Body;
            return mm;
        }

        private static void AddEmailAddress2List(string Emails, System.Collections.ArrayList eac)
        {
            if (Emails == null)
            {
                return;
            }
            string[] email = Emails.Split(';');
            foreach (var item in email)
            {
                if (Regex.IsMatch(item, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                    eac.Add(new EmailAddress(item));
            }
        }


        /*----------------------------------------------以下是imap.msg的代码-------------------------------------------*/

        private static Aspose.Network.Imap.ImapClient client = null;

        public static List<EmailInfo> CheckMails(string host, string port, string user, string psw)
        {
            //Logger.Info("MO:CM");
            //Logger.Info(host);
            //Logger.Info(port);
            //Logger.Info(user);
            //Logger.Info(psw);
            //Logger.Info("over"); 
            List<EmailInfo> list = new List<EmailInfo>();

            if (client == null)
            {
                Logger.Info("*init aspose");
                client = new Aspose.Network.Imap.ImapClient(host, Convert.ToInt32(port), user, psw);
            }
            client.Connect(true);
            client.SelectFolder("INBOX");
            client.Timeout = 60000;
            Aspose.Network.Imap.ImapMessageInfoCollection messageInfos;
            Logger.Info("*messageInfos = client.ListMessages();");
            messageInfos = client.ListMessages();
            foreach (Aspose.Network.Imap.ImapMessageInfo messageinfo in messageInfos)
            {
                if (!messageinfo.IsRead)
                {
                    Logger.Info("*foreach new mail");

                    EmailInfo ei = new EmailInfo();
                    ei.ID = messageinfo.UniqueId;
                    Aspose.Network.Mail.MailMessage mail_msg;
                    mail_msg = client.FetchMessage(ei.ID);
                    ei.Subject = mail_msg.Subject.Trim();
                    ei.CC = Convert.ToString(mail_msg.CC);
                    if (mail_msg.Body.Length > 350)
                        ei.Body = mail_msg.Body.Substring(0, 349);
                    else
                        ei.Body = mail_msg.Body;
                    ei.HtmlBody = mail_msg.HtmlBody;
                    ei.isHtmlBody = mail_msg.IsBodyHtml;
                    ei.From = Convert.ToString(mail_msg.From);
                    ei.Date = mail_msg.Date;
                    ei.To = Convert.ToString(mail_msg.To);
                    ei.Subject = ei.Subject.Replace("(Aspose.Network Evaluation)", "");
                    list.Add(ei);
                    ///*----------------------测试用messagebox封装后去掉，可以自己添加需要的测试--------------------------*/
                    //System.Windows.Forms.MessageBox.Show(ei.Sender);
                    //System.Windows.Forms.MessageBox.Show(Convert.ToString(ei.CC));
                    //System.Windows.Forms.MessageBox.Show(ei.Subject);
                    ///*----------------------测试用messagebox封装后去掉--------------------------*/
                }
            }

            return list;
        }


    }
}
